﻿using JinfuyuanProject.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace JinfuyuanProject.Filters
{
    public class LoginFilter : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var httpMethod = filterContext.HttpContext.Request.HttpMethod;

            //// 判断请求方法是否为 POST
            //if (httpMethod == "POST")
            //{
            //    return;
            //    // 执行 POST 请求特定的逻辑
            //}
            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) || filterContext.Controller.GetType().IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                //如果是允许匿名访问
                return;
            }
            //如果我要去登录页
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;//Home
            string actionName = filterContext.ActionDescriptor.ActionName;//Index
            string url = "/" + controllerName + "/" + actionName;
            List<string> all_page_list = HttpRuntime.Cache["all_page_list"] as List<string>;

            if (url.ToLower() != "/home/login".ToLower() && url.ToLower() != "/home/checklogin")
            {
                Staff user = filterContext.HttpContext.Session["user"] as Staff;
                if (user == null)
                {
                    //如果没有登录
                    filterContext.Result = new RedirectResult("/home/login");
                    return;
                }
                //如果登录了
                if (url.ToLower() == "/home/index".ToLower())
                {
                    //如果是首页
                    return;
                }
                //如果缓存中有该用户的url
                List<string> url_list = HttpRuntime.Cache[user.Id.ToString()] as List<string>;
                if (url_list != null && url_list.Contains(url.ToLower()))
                {
                    //如果url在缓存中
                    return;
                }
                if (all_page_list != null && !all_page_list.Contains(url.ToLower()))
                {
                    //如果url是接口
                    return;
                }

                //如果url不在缓存中，不是接口
                filterContext.Result = new RedirectResult("/home/error");

            }
            return;
        }
    }
}